import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Scanner;

import javax.imageio.ImageIO;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;




public class EditEvent {

	private int EVENTID; // event you are currently editing
	
	private PhoneLayout phone;
	
	private JButton cancelBut, updateEventBut, deleteBut;
	
	private JPanel cards;
	
	private HintTextField titleField, locationField,dateField, startField ,endField, repeatBox,tagField;
	
	private JComboBox repeatList;
	
	public EditEvent(PhoneLayout p){
		phone=p;
		cards = p.cards;

		
		/* add Event does not use the same bottom and top toolbar as the other screen */
		JPanel screenPanel = new JPanel();
		screenPanel = new JPanel();
		screenPanel.setLayout(new BoxLayout(screenPanel,BoxLayout.Y_AXIS));
		screenPanel.setBackground(Color.white);
		screenPanel.setMaximumSize(new Dimension(480,800));
		screenPanel.setMinimumSize(new Dimension(480,800));
		screenPanel.setPreferredSize(screenPanel.getMaximumSize());
		
		
		/* build top navigation bar*/
		JPanel topBar = new JPanel(new BorderLayout());
		topBar.setBackground(Color.darkGray);
		topBar.setPreferredSize(new Dimension(480,80));
		screenPanel.add(topBar);		
		
		JLabel title = new JLabel("   Edit Event");
		title.setForeground(Color.white);
		title.setFont(new Font("Arial",Font.PLAIN,25));
		topBar.add(BorderLayout.WEST, title);
		
		/* top buttons */
		JPanel buttonPanel = new JPanel();
		buttonPanel.setLayout(new BoxLayout(buttonPanel,BoxLayout.X_AXIS));
		buttonPanel.setBackground(Color.darkGray);
		buttonPanel.setPreferredSize(new Dimension(310, 80));
		
		TopButtonsActionListener topButListner = new TopButtonsActionListener();

		deleteBut = new JButton(" Delete ");
		deleteBut.addActionListener(topButListner);
		buttonPanel.add(deleteBut);
		
		buttonPanel.add(Box.createRigidArea(new Dimension(10,50))); // padding in middle
		
		cancelBut = new JButton(" Cancel ");
		cancelBut.addActionListener(topButListner);
		buttonPanel.add(cancelBut);
		
		buttonPanel.add(Box.createRigidArea(new Dimension(10,50))); // padding in middle
		
		updateEventBut = new JButton(" Update ");
		updateEventBut.addActionListener(topButListner);
		buttonPanel.add(updateEventBut);
		
		topBar.add(BorderLayout.EAST, buttonPanel);
		
		
		
		/* build main screen THE MIDDLE WHITE BIT*/
		
		JPanel mainScreen= new JPanel(); 
		mainScreen.setLayout(new BoxLayout(mainScreen,BoxLayout.Y_AXIS));

		
		mainScreen.setBorder(new EmptyBorder(20,10,20,10)); // padding
		mainScreen.setBackground(Color.white);
		mainScreen.setPreferredSize(new Dimension(480,720));
		
		
		Font inputFont = new Font("Arial",Font.PLAIN,20);
		
		titleField = new HintTextField("Title");
		titleField.setToolTipText("Title");
		titleField.setFont(inputFont);
		mainScreen.add(titleField);
		
		locationField = new HintTextField("Location");
		locationField.setToolTipText("Location");
		locationField.setFont(inputFont);
		mainScreen.add(locationField);
		
		mainScreen.add(Box.createRigidArea(new Dimension(50,50))); // padding in middle
		
		dateField = new HintTextField("Date (e.g 14/11/2011)");
		dateField.setToolTipText("Start");
		dateField.setFont(inputFont);
		mainScreen.add(dateField);
		
		JPanel timePanel = new JPanel();
		timePanel.setLayout(new BoxLayout(timePanel,BoxLayout.X_AXIS));
		timePanel.setBackground(Color.white);
		startField = new HintTextField("Start Time (e.g 14:30)");
		startField.setToolTipText("Start Time. 24hr format");
		startField.setFont(inputFont);
		timePanel.add(startField);
		
		endField = new HintTextField("End Time (e.g 15:30)");
		endField.setToolTipText("End Time. 24hr format");
		endField.setFont(inputFont);
		timePanel.add(endField);
		
		mainScreen.add(timePanel);
		

		mainScreen.add(Box.createRigidArea(new Dimension(50,15))); // padding in middle
		
		JPanel recurrencePanel = new JPanel();
		recurrencePanel.setLayout(new BoxLayout(recurrencePanel,BoxLayout.X_AXIS));
		recurrencePanel.setBackground(Color.white);

		JLabel reccurenceLabel = new JLabel("Recurrence: ");
		reccurenceLabel.setFont(inputFont);
		recurrencePanel.add(reccurenceLabel);

		String[] recurrenceStrings = { "None", "Daily", "Twice a Week", "Four times a Week" };
		repeatList = new JComboBox(recurrenceStrings);
		repeatList.setFont(inputFont);
		repeatList.setSelectedIndex(0);
		repeatList.addActionListener(topButListner);
		recurrencePanel.add(repeatList);
		
		mainScreen.add(recurrencePanel);

		
		mainScreen.add(Box.createRigidArea(new Dimension(50,50))); // padding in middle

		
		tagField = new HintTextField("Tags (e.g lunch, west end, pub) ");
		tagField.setToolTipText("Tag");
		tagField.setFont(inputFont);
		mainScreen.add(tagField);
		

		screenPanel.add(mainScreen);
		
		
		
		
		// add to cards 
		phone.cards.add(screenPanel, "EDIT_EVENT");
		
		
		
		//phone.mainScreenP.add(new JLabel("Hello"));
		
		
		//this.phone.mainScreenP.setBackground(Color.black);
		
		
		
	}
	
	/* THIS IS WHERE THE MAGIC HAPPENS */
	public void editEventID(int id){
		showEvent(phone.cal.getAppointmentByID(id));
		EVENTID=id;
	}
	
	
	class TopButtonsActionListener implements ActionListener{
		
		public TopButtonsActionListener(){
		}
		public void actionPerformed(ActionEvent ae) {	
			CardLayout cl = (CardLayout)(cards.getLayout());

			if (ae.getSource()==deleteBut){
				System.out.println("Delete Button Pressed");
				// delte the event here
				phone.cal.removeAppointment(phone.cal.getAppointmentByID(EVENTID));
				updateOtherScreen();// refresh all other screens as an appointment is now removed
				cl.show(cards, "home");

			}
			else if(ae.getSource()==cancelBut){
				System.out.println("Cancel Button Pressed");
				phone.swipeLeftBut.setEnabled(true);
				phone.swipeRightBut.setEnabled(true);
				updateOtherScreen();// refresh all other screens as an appointment is now removed
				cl.show(cards, "home");
			}
			else if (ae.getSource()==updateEventBut){
				
				phone.cal.removeAppointment(phone.cal.getAppointmentByID(EVENTID));

				
				int start_day, end_day, start_month, end_month, start_year, end_year;
				
				
				System.out.println("Update Button Pressed");
			
				CalendarDate cd = parseDate(dateField.getText());
				System.out.println(cd);
				CalendarTime st = parseTime(startField.getText());
				CalendarTime et = parseTime(endField.getText());
				String title = titleField.getText();
				if (cd!=null && st!=null && et!=null && title!=null){
					Appointment ap = new Appointment(cd, st, et, title, locationField.getText(), tagField.getText(), Appointment.RecurrenceFromInt(repeatList.getSelectedIndex()), 0);
					phone.cal.addAppointment(ap);
					System.out.println(ap.getID());
					System.out.println("Saving");
					phone.cal.saveCalendar("./calendar.txt");
					resetScreen();
					phone.swipeLeftBut.setEnabled(true);
					phone.swipeRightBut.setEnabled(true);
					cl.show(cards, "home");
				}
				else{ // make the bad formatted items red!
					if (cd == null)
						dateField.setForeground(Color.red);
					else
						dateField.setForeground(Color.black);
					if (st == null)
						startField.setForeground(Color.red);
					else
						startField.setForeground(Color.black);
					if (et == null)
						endField.setForeground(Color.red);	
					else
						endField.setForeground(Color.black);
					if (title == "")
						titleField.setForeground(Color.red);
					else
						titleField.setForeground(Color.black);
				}

				
			}
//			else if (ae.getSource()==searchBut)
//				System.out.println("Search Button Pressed");
//			else if (ae.getSource()==filterBut)
//				System.out.println("Filter Button Pressed");
//			else if (ae.getSource()==settingsBut)
//				System.out.println("Settings Button Pressed");
//		}
		

		}
	}
	
	/* dateStr should be formatted like 14/11/1990*/
	public CalendarDate parseDate(String dateStr){
		try{
			int day, month, year;
			Scanner dateScanner = new Scanner(dateStr);
			dateScanner.useDelimiter("/");
			day=Integer.parseInt(dateScanner.next());
			month=Integer.parseInt(dateScanner.next());
			year=Integer.parseInt(dateScanner.next());
			if (day>31 || month>12){
				System.out.println(dateStr + " is invalid! day or month out of range. ");
				return null;
			}
			return new CalendarDate(day,month,year);
		}
		catch(Exception e){
			System.out.println(dateStr + " is invalid! Format is dd/mm/yyyy ");
			return null;
		}
	}
	
	/* dateStr should be formatted like 14:30 */
	public CalendarTime parseTime(String timeStr){
		try{
			int hour, min;
			Scanner timeScanner = new Scanner(timeStr);
			timeScanner.useDelimiter(":");
			hour=Integer.parseInt(timeScanner.next());
			min=Integer.parseInt(timeScanner.next());
			if (hour>24 || hour<0 || min>59 || min<0){
				System.out.println(timeStr + " is invalid! hour or min out of range. ");
				return null;
			}
			return new CalendarTime(hour,min);
		}
		catch(Exception e){
			System.out.println(timeStr + " is invalid! Format is hh:mm ");
			return null;
		}
	}
	
	/* call this after successful add to reset all the fields */
	private void resetScreen(){
		titleField.setText("Title");
		locationField.setText("Location");
		dateField.setText("Date (e.g 14/11/2011)");
		startField.setText("Start Time (e.g 14:30)");
		endField.setText("End Time (e.g 15:30)");
		tagField.setText("Tags (e.g lunch, west end, pub) ");
		repeatList.setSelectedIndex(0);		
		dateField.setForeground(Color.black);
		startField.setForeground(Color.black);
		endField.setForeground(Color.black);
		titleField.setForeground(Color.black);
	}
	
	

	
	/* used for EDIT EVENT TO FILL IN FIELDS */
	private void showEvent(Appointment ap){
		titleField.setText(ap.description);
		locationField.setText(ap.location);
		dateField.setText(ap.date.toString());
		startField.setText(ap.start_time.toString());
		endField.setText(ap.end_time.toString());
		tagField.setText(ap.category);
		repeatList.setSelectedIndex(Appointment.IntFromRecurrence(ap.recur));		
		dateField.setForeground(Color.black);
		startField.setForeground(Color.black);
		endField.setForeground(Color.black);
		titleField.setForeground(Color.black);
	}
	
	/* can be used to set the jtextfields from other sceens */
	public void setDateField(String s){
		dateField.setText(s);
	}
	
	public void setStartField(String s){
		startField.setText(s);
	}
	
	private void  updateOtherScreen(){
		phone.updateAgendaView();
		phone.updateDayView();

	}
}
